package com.apes.scm.voucher.service.ict;

import com.apes.framework.api.SpringManager;
import com.apes.scm.account.tax.model.Tax;
import com.apes.scm.account.tax.service.TaxService;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.masterdata.party.service.PartyRoleService;
import com.apes.scm.masterdata.product.model.Product;

/**
 * 功能：公司间/跨公司交易
 *
 * @author xul
 * @create 2018-10-18 11:25
 */
public abstract class AbstractIct implements Ict {

    protected String[] BusinessTypes;

    /**
     * 功能：业务单据类型
     */
    @Override
    public String[] getBusinessTypes() {
        return BusinessTypes;
    }


    /**
     * 销项税
     */
    protected Tax getSaleTax(PartyRole company, Product product) {
        return SpringManager.getBean(TaxService.class).getSaleTax(company, product);
    }

    /**
     * 进项税
     */
    protected Tax getPurchaseTax(PartyRole company, PartyRole supplier, Product product) {
        return SpringManager.getBean(TaxService.class).getPurchaseTax(company, supplier, product);
    }

    /**
     * 公司
     */
    protected PartyRole getCompany(PartyRole owner) {
        owner = loadPartyRole(owner.getId());
        PartyRole customer = SpringManager.getBean(PartyRoleService.class).findByPartyAndRole(owner.getParty().getId(), "Company");
        if (customer == null) throw new RuntimeException("内部公司：" + owner.getName() + " 没有定义公司角色，不允许跨公司交易！");
        return customer;
    }

    /**
     * 客户
     */
    protected PartyRole getCustomer(PartyRole owner) {
        // 刷新数据
        owner = loadPartyRole(owner.getId());
        PartyRole customer = SpringManager.getBean(PartyRoleService.class).findByPartyAndRole(owner.getParty().getId(), "Customer");
        if (customer == null) throw new RuntimeException("内部公司：" + owner.getName() + " 没有定义客户角色，不允许跨公司交易！");
        return customer;
    }

    /**
     * 供应商
     */
    protected PartyRole getSupplier(PartyRole owner) {
        // 刷新数据
        owner = loadPartyRole(owner.getId());
        PartyRole customer = SpringManager.getBean(PartyRoleService.class).findByPartyAndRole(owner.getParty().getId(), "Supplier");
        if (customer == null) throw new RuntimeException("内部公司：" + owner.getName() + " 没有定义供应商角色，不允许跨公司交易！");
        return customer;
    }

    /*
    * 刷新partyRole
    * */
    private PartyRole loadPartyRole(String id) {
       return SpringManager.getBean(PartyRoleRepository.class).findOne(id);
    }


}
